/*
 * FileLoader.cpp
 *
 *  Created on: 01.09.2012
 *      Author: caffeine
 */

#include "FileLoader.h"
#include <StringUtils.h>
#include "../irr/Utils.h"
#include <log/Log.h>
#include "../irr/gui/IElementImage.h"
#include "../irr/gui/Path9Image.h"
#include "../irr/gui/Image.h"
#include <exception/IO.h>

irr::IrrlichtDevice*device=0;

void FileLoader::setIrrDevice(irr::IrrlichtDevice*d){
	device=d;
}

irr::scene::ISceneNode*FileLoader::getNode(irr::core::stringc path,irr::scene::ISceneNode*parent){
	if (!device->getFileSystem()->existFile(path)){
		GEN_IO_ERROR(irr::core::stringc("Can't load model: file \"")+path+irr::core::stringc("\" not found"));
        return 0;
    }

	irr::xml::IXmlNode*ter=device->getFactoryEnvironment()->getXmlTree(path);
	device->getFactoryEnvironment()->runNode(ter);
	irr::scene::ISceneNode*res=(irr::scene::ISceneNode*)ter->getTag();
	res->setParent(parent);
	ter->drop();
	return res;
}

irr::scene::IAnimatedMeshSceneNode*FileLoader::getModel(irr::core::stringc path,irr::scene::ISceneNode*parent){
	if (!device->getFileSystem()->existFile(path)){
		GEN_IO_ERROR(irr::core::stringc("Can't load model: file \"")+path+irr::core::stringc("\" not found"));
        return 0;
    }
	/*UN SUPPORTED XML MODEL
    if (path.endWith(".xml")){
        return (irr::scene::IAnimatedMeshSceneNode*)XmlUtils::getModel(path,parent);
    }
    */
    //LOG("try get model %s",path.c_str());
    irr::scene::IAnimatedMesh*mesh=0;
    try{
		mesh=device->getSceneManager()->getMesh(path);
    }catch(...){
    	LOGE("UNKNOWN ERROR!");
    	return 0;
    }
    if (!mesh){
		GEN_IO_ERROR(irr::core::stringc("Can't load model: in file \"")+path+irr::core::stringc("\" model not found"));
        return 0;
    }
    irr::scene::IAnimatedMeshSceneNode*node=device->getSceneManager()->addAnimatedMeshSceneNode(mesh,parent);
    if (node)
    	node->setMaterialFlag(irr::video::EMF_LIGHTING,false);
    return node;
}

irr::gui::IElementImage*FileLoader::createElementImage(irr::io::path path){
	if (path=="")
		return 0;

	if (!irr::utils::fileExist(path)){
		//LOGE("Can't find image file \"%s\"",path.c_str());
		GEN_IO_ERROR(irr::core::stringc("Can't load image: file \"")+path+irr::core::stringc("\" not found"));
		return 0;
	}
	irr::io::path pathext=path;
	pathext.make_lower();
	if (pathext.endWith(".9.png"))
		return irr::gui::Path9Image::createPath9Image(device->getVideoDriver(),path);
	return irr::gui::Image::createImage(device->getVideoDriver(),path);
}
